package com.wandian.audio.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import androidx.annotation.Nullable;

import com.mylib.libcore.AppContext;
import com.mylib.libcore.eventbus.ChangeMessage;
import com.mylib.libcore.mediaplayer.ManagedMediaPlayer;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.RetrofitUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.wandian.audio.bean.MusicBean;
import com.wandian.audio.bean.MusicURLBean;
import com.wandian.audio.config.AudioConfig;
import com.wandian.audio.data.BaseAppApi;
import com.wandian.audio.tools.AudioFocusManager;
import com.wandian.audio.tools.AudioNotificationUtil;
import com.wandian.audio.tools.MusicCollector;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.wandian.audio.config.AudioConfig.AUDIONEXT;
import static com.wandian.audio.config.AudioConfig.AUDIOUP;
import static com.wandian.audio.config.AudioConfig.AUDIO_MAX_DURATION;
import static com.wandian.audio.config.AudioConfig.AUDIO_PLAY_LIST;
import static com.wandian.audio.config.AudioConfig.AUDIO_PLAY_MODEL_KEY;
import static com.wandian.audio.config.AudioConfig.AUDIO_PLAY_RANDOM;
import static com.wandian.audio.config.AudioConfig.AUDIO_SELECT_MUSIC_INDEX;


/**
 * @author Administrator
 * @date 2020/3/25-15:09
 * @description
 **/
public class AudioService extends Service implements AudioFocusManager.OnAudioFocusChangeListener {

    private final static  String  TAG = "AudioServiceLog";
    private ManagedMediaPlayer mMediaPlayer;
    //    private  WifiManager.WifiLock wifiLock;
    private AudioBinder binder;
    private String notification_key="";
    private int musicIndex = -1;
    private MusicBean musicBean;
    private String nowUrlID="";
    private String musicRealUrl="";
    private AudioFocusManager audioFocusManager;//音频焦点获取
    private AudioNotificationUtil mAudioNotificationUtils;//通知栏
    private  Retrofit retrofit;
    private int reTimes = 0;//重复尝试
    private boolean prepareSuccess = false;//准备完成
    private boolean mResumeAfterCall = false;//电话状态监听事件
    @Override
    public void onCreate() {
        super.onCreate();
        binder = new AudioBinder();
        EventBus.getDefault().post(new ChangeMessage("createMusicService",""));
        Log.d(TAG,"onCreate");
        //创建音频管理
        createAudioManager();
        //开启通知栏
        mAudioNotificationUtils = new AudioNotificationUtil(this,musicBean);
        mAudioNotificationUtils.showNotification();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //每次更新获取intent数据
        if(!UIUtils.isEmpty(intent)){
            String music_index = intent.getStringExtra("music_index");
            if(!UIUtils.isEmpty(music_index)) musicIndex = Integer.parseInt(music_index);
            notification_key = intent.getStringExtra("key");
        }
        if(!UIUtils.isEmpty(notification_key)){
            switch (notification_key){
                case AUDIOUP:
                    binder.playUpLevel();
                    break;
                case AUDIONEXT:
                    binder.playNextLevel();
                    break;
                case AudioConfig.AUDIOCONTORL:
                    binder.upDataAudioPlayState();
                    break;
            }
            notifyUpDataUi();
        }else {
            Log.d(TAG,musicIndex+"");
            //开始播放音乐
            if(UIUtils.isEmpty(binder)){
                binder = new AudioBinder();
            }
            if(musicIndex!=-1){
                binder.playItem();
                notifyUpDataUi();
            }
        }
        Log.d(TAG,notification_key+"=musicIndex="+musicIndex);
        //START_STICKY：//如果service进程被kill掉，保留service的状态为开始状态，但不保留递送的intent对象。随后系统会尝试重新创建service，由于服务状态为开始状态，所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service，那么参数Intent将为null。
        // START_NOT_STICKY：//“非粘性的”。使用这个返回值时，如果在执行完onStartCommand后，服务被异常kill掉，系统不会自动重启该服务。
        // START_REDELIVER_INTENT：//重传Intent。使用这个返回值时，如果在执行完onStartCommand后，服务被异常kill掉，系统会自动重启该服务，并将Intent的值传入。
        // START_STICKY_COMPATIBILITY：//START_STICKY的兼容版本，但不保证服务被kill后一定能重启
        return  START_NOT_STICKY;
        // return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    class  AudioBinder extends Binder implements AudioInService {
        public void playItem(){

            if(UIUtils.isEmpty(mMediaPlayer)){
                if(musicIndex<0) return;
                startPlayMusic();
            }else {
                if(UIUtils.isEmpty(MusicCollector.getSongsList()) || MusicCollector.getSongsList().size()<=musicIndex){
                    ToastUtil.show("歌曲数据错误！");
                    return;
                }
                musicBean =  MusicCollector.getSongsList().get(musicIndex);
                Log.d(TAG,nowUrlID+"===123===="+MusicCollector.getSongsList().get(musicIndex).getId()+"");
                if(!nowUrlID.equals(MusicCollector.getSongsList().get(musicIndex).getId()+"") ){
                    startPlayMusic();
                }
            }
        }

        @Override
        public boolean isPlay(){
            if(UIUtils.isEmpty(mMediaPlayer))  return  false;
            return mMediaPlayer.isPlaying();
        }

        /**
         * 获取总进度
         * @return
         */
        @Override
        public int getDuration() {
            if(UIUtils.isEmpty(mMediaPlayer) || UIUtils.isEmpty(mMediaPlayer.getDuration()) ){
                return 100;
            }else {
                if(mMediaPlayer.getDuration()>AUDIO_MAX_DURATION)return 100;
                return mMediaPlayer.getDuration();
            }
        }

        /**
         * 获取当前进度
         * @return
         */
        @Override
        public int getProgress() {
            if(UIUtils.isEmpty(mMediaPlayer) || UIUtils.isEmpty(mMediaPlayer.getCurrentPosition()) ){
                return 0;
            }else {
                if(mMediaPlayer.getCurrentPosition()>AUDIO_MAX_DURATION){
                    return 0;
                }
                return mMediaPlayer.getCurrentPosition();
            }
        }

        /**
         * 播放上一级
         * @return
         */
        @Override
        public void playUpLevel() {
            Log.d(TAG,"playUpLevel");
            playLastSong();
        }

        /**
         * 播放下一级
         * @return
         */
        @Override
        public void playNextLevel() {
            Log.d(TAG,"playNextLevel");
            playCompleteMusic();
        }

        /**
         * 播放暂停
         * @return
         */
        @Override
        public void pauseVideo() {
            Log.d(TAG,"pauseVideo");
            pausePlayMusic();
        }

        /**
         * 滑动指定位置播放
         * @return
         */
        @Override
        public void seekTo(int duration) {
            if(mMediaPlayer == null)
                return;
            mMediaPlayer.seekTo(duration);
            mMediaPlayer.start();
            if(audioFocusManager != null)audioFocusManager.requestFocus();
        }

        /**
         * 指定播放某一首
         * @return
         */
        @Override
        public void playItemMusic(int index) {
            musicIndex = index;
            playMusic();
        }

        /**
         * 更新播放状态
         */
        @Override
        public void upDataAudioPlayState() {
            //切换播放状态
            if(!UIUtils.isEmpty(mMediaPlayer)){
                if(isPlay()){//正在播放
                    mMediaPlayer.pause();
                }else {
                    mMediaPlayer.start();
                    if(audioFocusManager != null)audioFocusManager.requestFocus();
                }
                notifyUpDataUi();
            }
        }
    }

    //开始播放
    private void startPlayMusic(){
        stopPlayMusic();
        playMusic();
    }


    //播放完成获取下一曲坐标
    private void getNextIndex(){
        //获取播放模式
        String playModel = AppContext.getInstance().getAppPreferencesHelper().getKeyValue(AUDIO_PLAY_MODEL_KEY);
        if(UIUtils.isEmpty(playModel)){
            playModel = AUDIO_PLAY_LIST;
        }

        switch (playModel){
            case AUDIO_PLAY_LIST:
                musicIndex++;
                break;
            case AUDIO_PLAY_RANDOM:
                if(musicIndex<0)musicIndex=0;
                musicIndex=MusicCollector.getRandomMusicNextIndex(musicIndex);
                break;
        }
        if(musicIndex>= MusicCollector.getSongsList().size()){
            musicIndex = 0;
        }
    }

    //播放上一曲
    private void playLastSong(){
        musicIndex--;
        if(musicIndex<0) musicIndex = 0;
        playMusic();
    }

    //播放完成开始下一曲音乐
    private void playCompleteMusic(){
        getNextIndex();
        playMusic();
    }

    //暂停播放
    private void pausePlayMusic(){
        if(!UIUtils.isEmpty(mMediaPlayer)){
            mMediaPlayer.pause();
            notifyUpDataUi();
        }
    }

    //播放
    private void playingMusic(){
        if(!UIUtils.isEmpty(mMediaPlayer)){
            mMediaPlayer.start();
            notifyUpDataUi();
        }
    }

    //结束播放
    private void stopPlayMusic(){
        if(!UIUtils.isEmpty(mMediaPlayer)){
            try {
                mMediaPlayer.stop();
                mMediaPlayer.release();
                mMediaPlayer=null;
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }
    }

    //播放
    private void playMusic(){
        if(mMediaPlayer == null) {
            mMediaPlayer = new ManagedMediaPlayer();
        }else {
            mMediaPlayer.reset();
        }
        //创建音频监听管理器
        createAudioManager();

        musicBean =  MusicCollector.getSongsList().get(musicIndex);
        nowUrlID = musicBean.getId()+"";
        //缓存播放musicIndex
        AppContext.getInstance().getAppPreferencesHelper().setKeyValue(AUDIO_SELECT_MUSIC_INDEX,musicIndex+"");
        if(UIUtils.isEmpty(musicBean.getUrl())){
            getMusicUrl(musicBean.getId());
        }else {
            playMusicByIDorURL(musicBean.getUrl());
        }

    }

    private void  playMusicByIDorURL(String url){
        prepareSuccess = false;
        try {
            if(UIUtils.isEmpty(url)){
                ToastUtil.show("歌曲数据异常");
                return;
            }
            Log.d(TAG,"播放url======>"+url);


            mMediaPlayer.setDataSource(url);//进入初始态
            mMediaPlayer.prepareAsync();//异步准备
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    Log.d(TAG,"播放准备完成-回调" );
                    prepareSuccess = true;
                    reTimes=0;
                    mMediaPlayer.start(); // 准备好了再播放
                    if(audioFocusManager != null)audioFocusManager.requestFocus();
                    notifyUpDataUi();
                }
            });
            //监听播放是否完成
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    Log.d(TAG,"播放完毕-回调"+prepareSuccess+"==="+mMediaPlayer.getDuration());
                    if(mMediaPlayer.getDuration()>1000 && mMediaPlayer.getDuration()<AUDIO_MAX_DURATION  && mMediaPlayer.getCurrentPosition()>(mMediaPlayer.getDuration()-1000) && prepareSuccess) {
                        Log.d(TAG,"播放完毕"+mMediaPlayer.getDuration());
                        playCompleteMusic();
                    }
                }
            });
            //监听播放错误
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    // ToastUtil.show("播放异常，进入下一曲"+nowUrl);
                    Log.d(TAG,"播放异常，进入下一曲"+musicBean.getUrl());
                    reTimes++;
                    if(reTimes>2){
                        reTimes=0;
                        playCompleteMusic();
                    }else {
                        playMusic();
                    }
                    return true;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //通知页面刷新
    private void notifyUpDataUi(){
        EventBus.getDefault().post(new ChangeMessage("notifyUpDataAudioUi",musicIndex+""));
        if(UIUtils.isEmpty(mAudioNotificationUtils)){
            mAudioNotificationUtils = new AudioNotificationUtil(this,musicBean);
            mAudioNotificationUtils.showNotification();
        } else {
            if(!UIUtils.isEmpty(mMediaPlayer)){
                mAudioNotificationUtils.AudioNotify(this,musicBean,  mMediaPlayer.isPlaying());
            }
        }
    }

    //创建音频管理
    private void createAudioManager(){
        if(audioFocusManager == null){
            audioFocusManager = new AudioFocusManager(this);
            audioFocusManager.setOnAudioFocusChangeListener(this::onAudioFocusChange);
        }
    }

    //音频焦点监听
    @Override
    public void onAudioFocusChange(int focusChange) {
        switch (focusChange) {
            case AudioManager.AUDIOFOCUS_GAIN://// 你已经得到了音频焦点。
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:// 你暂时失去了音频焦点，但你可以小声地继续播放音频（低音量）而不是完全扼杀音频。
                playingMusic();
                if(audioFocusManager != null)audioFocusManager.requestFocus();
                break;
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT://// 你暂时失去了音频焦点
                if(audioFocusManager != null)audioFocusManager.releaseAudioFocus();
                //监听来电状态
                telephony();
                break;
            case AudioManager.AUDIOFOCUS_LOSS://// 你已经失去了音频焦点很长时间了。你必须停止所有的音频播放
                pausePlayMusic();
                if(audioFocusManager != null)audioFocusManager.releaseAudioFocus();
                break;
       }
    }

    //来电监听
    private void telephony() {
        //获得相应的系统服务
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if(tm != null) {
            try {
                MyPhoneCallListener myPhoneCallListener = new MyPhoneCallListener();
                myPhoneCallListener.setCallListener(new MyPhoneCallListener.CallListener() {
                    @Override
                    public void onCallRinging(int state) {
                        //回调，做你想做的，我是关闭当前界面
                        switch (state) {
                            case TelephonyManager.CALL_STATE_IDLE:// 电话挂断
                                playingMusic();
                                if(audioFocusManager != null)audioFocusManager.requestFocus();
                                break;
                            case TelephonyManager.CALL_STATE_OFFHOOK: //电话通话的状态
                            case TelephonyManager.CALL_STATE_RINGING: //电话响铃的状态
                                pausePlayMusic();
                                break;
                        }

                    }
                });
                // 注册来电监听
                tm.listen(myPhoneCallListener, PhoneStateListener.LISTEN_CALL_STATE);
            } catch(Exception e) {
                // 异常捕捉
            }
        }
    }

    private void getMusicUrl(String musicId){
        //创建Retrofit对象
        if(retrofit == null) retrofit = RetrofitUtil.createMusicOtherRetrofit();
        //创建网络请求接口实例
        BaseAppApi request = retrofit.create(BaseAppApi.class);
        Map<String, String> map = new HashMap<>();
        map.put("id", musicId);
        Log.d("getMusicURL", "getMusicURL="+ musicId);
        Call<Object> call = request.getMusicURL(map);
        //发送网络请求(异步)
        call.enqueue(new Callback<Object>() {
            @Override
            public void onResponse(Call<Object> call, Response<Object> response) {

                if(UIUtils.isEmpty(response.body())){
                    return;
                }
                Log.d("getMusicURL", "getMusicURL="+ JsonUtil.toJson(response.body()));
                if(UIUtils.isEmpty(response.body())){
                    return;
                }
                MusicURLBean bean = (MusicURLBean) JsonUtil.parseJsonToBean(JsonUtil.toJson(response.body()),MusicURLBean.class);
                if(!UIUtils.isEmpty(bean) && bean.getData().size()>0){
                    musicRealUrl = bean.getData().get(0).getUrl();
                    if(musicIndex<MusicCollector.getSongsList().size()){
                        MusicCollector.getSongsList().get(musicIndex).setUrl(musicRealUrl);
                    }
                    Log.d("getMusicURL", "getMusicURL="+musicRealUrl);
                    playMusicByIDorURL(musicRealUrl);
                    //listData.setValue(bean.getHotAlbums());
                }else {
                    musicRealUrl="";
                    ToastUtil.show("网络错误");
                }
            }

            @Override
            public void onFailure(Call<Object> call, Throwable t) {
                musicRealUrl="";
                ToastUtil.show("网络错误");
                Log.d("getMusicSinger", "error="+t.getMessage());
            }
        });
    }
}
